/**
 * 构建配置
 * 统一管理不同环境的构建配置
 */

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import { viteMockServe } from 'vite-plugin-mock'
import eslint from 'vite-plugin-eslint'
import { getEnvConfig } from './env'

// 构建配置
export const createBuildConfig = (mode: string) => {
  const env = loadEnv(mode, process.cwd(), '')
  const envConfig = getEnvConfig()
  
  return defineConfig({
    plugins: [
      vue(),
      // 自动导入API
      AutoImport({
        imports: [
          'vue',
          'vue-router',
          'pinia',
          {
            'element-plus': [
              'ElMessage',
              'ElMessageBox',
              'ElNotification',
              'ElLoading'
            ]
          }
        ],
        resolvers: [ElementPlusResolver()],
        dts: true,
        eslintrc: {
          enabled: true
        }
      }),
      // 自动导入组件
      Components({
        resolvers: [ElementPlusResolver()],
        dts: true
      }),
      // SVG图标
      createSvgIconsPlugin({
        iconDirs: [resolve(process.cwd(), 'src/assets/icons')],
        symbolId: 'icon-[dir]-[name]'
      }),
      // Mock数据
      viteMockServe({
        mockPath: 'mock',
        enable: envConfig.features.mock && mode === 'development',
        watchFiles: true
      }),
      // ESLint
      eslint({
        cache: false,
        include: ['src/**/*.vue', 'src/**/*.ts', 'src/**/*.tsx']
      })
    ],
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
        '#': resolve(__dirname, 'types')
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          api: 'modern-compiler',
          additionalData: `@use "@/styles/variables.scss" as *;`
        }
      }
    },
    server: {
      host: envConfig.app.host,
      port: envConfig.app.port,
      open: true,
      cors: true,
      proxy: {
        '/api': {
          target: envConfig.api.baseUrl,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    build: {
      target: 'es2015',
      outDir: 'dist',
      assetsDir: 'assets',
      sourcemap: envConfig.features.sourcemap,
      rollupOptions: {
        output: {
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
          manualChunks: {
            vue: ['vue', 'vue-router', 'pinia'],
            elementPlus: ['element-plus'],
            utils: ['axios', 'dayjs', 'lodash-es']
          }
        }
      },
      chunkSizeWarningLimit: 2000
    },
    define: {
      __VUE_OPTIONS_API__: false,
      __VUE_PROD_DEVTOOLS__: envConfig.features.devtools
    }
  })
}
